package com.xyx.spring.xyxLibraries.DaoImpl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import com.xyx.spring.Dao.BaseDao;
import com.xyx.spring.Utils.DaoUtil;
import com.xyx.spring.Utils.DataWrapper;
import com.xyx.spring.xyxLibraries.Dao.BookDao;
import com.xyx.spring.xyxLibraries.Entity.Book;
@Repository
public class BookDaoImpl extends BaseDao<Book> implements BookDao {

	@Override
	public boolean addBook(Book book) {
		// TODO Auto-generated method stub
		return save(book);
	}

	@Override
	public boolean deleteBook(Long bookId) {
		// TODO Auto-generated method stub
		return delete(get(bookId));
	}

	@Override
	public Book getBookById(Long bookId) {
		// TODO Auto-generated method stub
		return get(bookId);
	}

	@Override
	public DataWrapper<List<Book>> getBookList(Book book, Integer pageIndex, Integer pageSize) {
		// TODO Auto-generated method stub
		DataWrapper<List<Book>> result = new DataWrapper<List<Book>>();
		List<Book> ret = new ArrayList<Book>();
		Session session = getSession();
		Criteria criteria = session.createCriteria(Book.class);
		criteria.add(Restrictions.eq("bookTagId", book.getBookTagId()));
		if(book.getBookName()!=null){
			criteria.add(Restrictions.like("bookName","%"+ book.getBookName()+"%"));
		}
		if(book.getIntro()!=null){
			criteria.add(Restrictions.like("intro","%"+ book.getIntro()+"%"));
		}
		if (pageSize == null) {
			pageSize = 10;
		}
        if (pageIndex == null) {
        	pageIndex = 0;
		}
        // 取总页数
        criteria.setProjection(Projections.rowCount());
        int totalItemNum = ((Long)criteria.uniqueResult()).intValue();
        int totalPageNum = DaoUtil.getTotalPageNumber(totalItemNum, pageSize);

        // 真正取值
        criteria.setProjection(null);
        if (pageSize > 0 && pageIndex > 0) {
            criteria.setMaxResults(pageSize);// 最大显示记录数
            criteria.setFirstResult((pageIndex - 1) * pageSize);// 从第几条开始
        }
        try {
            ret = criteria.list();
        }catch (Exception e){
            e.printStackTrace();
        }
        result.setData(ret);
        result.setTotalNumber(totalItemNum);
        result.setCurrentPage(pageIndex);
        result.setTotalPage(totalPageNum);
        result.setNumberPerPage(pageSize);

        return result;
	}

}
